
  {extend name="public/base"}
  {block name="x-body"}
  <style>
      .layui-form-item .layui-input-inline {
          width: 30%;
      }

      .layui-form-item .layui-input-inline {
          width: 30%;
      }

      .layui-form-switch {
          margin-top: 8px;
      }

      #is_free_shipping span {
          display: {if isset($result)}{if $result.is_free_shipping == 0}inline-block{else /}none{/if}{else /}none{/if};
      }

      #is_free_shipping .layui-form-switch {
          margin-top: {if isset($result)}{if $result.is_free_shipping == 0}0{else /}8{/if}{else /}8{/if}px;
      }

      #is_free_shipping .layui-form-select {
           display: {if isset($result)}{if $result.is_free_shipping == 0}inline-block{else /}none{/if}{else /}none{/if};
      }

      #cate {
          display: flex;
      }

      #cate div {
          margin-right: 1%;
          display: none;
      }

      #cate div:first-of-type{
          display: block;
      }

      #cate div:last-of-type{
          display: block;
      }

      #cate > div:nth-last-child(2){
          margin-right: 10px;
      }

      #spec_table table {
          width: 100.03%;
      }

      #spec tr td > div {
          display: inline-block;
          margin-right: 15px;
      }

      #spec tr td > div > div:last-of-type {
          width: 30px;
          height: 30px;
          line-height: 30px;
          margin-top: 3px;
          vertical-align: middle;
          overflow: hidden;
          display: inline-block;
      }

      #spec tr td > div > div:last-of-type > img {
          width: 100%;
      }

      #spec tr td > div > div:last-of-type > i {
          font-size: 30px;
          position: relative;
          top: 2px;
      }


      #spec tr td > div > div:first-of-type {
          margin-right: 3px;
      }

      #attr tr td input {
          height: 30px;
      }

      #spec_item tr td > input {
          height: 30px;
      }

      #spec_item tr td:last-of-type > div {
          margin-top: 0;
      }

      #test9, #test12 {
          display: none;
      }

      #demo1{
          width: 200px;
      }

      .show_img {
          position: relative;

          width: 92px;
          height: 92px;
          text-align: center;
          display: inline-block;

          margin: 0 10px 10px 0;
      }

      .show_img img {
          width: 100%;
          height: 100%;
      }

      .show_img span {
          width: 100%;
          display: block;
          background: green;
          color: white;
          position: absolute;
          bottom: 0;
          left: 0;
      }

      .show_img div {
          width: 100%;
          height: 100%;
          background: rgba(35, 35, 35, .7);
          z-index: 99;
          position: absolute;
          left: 0;
          top: 0;
      }

      .show_img div i {
          font-size: 60px;
          color: #9c9898;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
      }

      .is_del {
          cursor: pointer;
          display: none;
      }
  </style>
    <div class="x-body">
        <form class="layui-form">
            <div class="layui-tab">
                <ul class="layui-tab-title">
                    <li class="layui-this">基本设置</li>
                    <li>商品相册</li>
                    <li>商品模型</li>
                    <li>积分兑换</li>
                </ul>
                <div class="layui-tab-content">

                    <!-- 基本设置 -->
                    <div class="layui-tab-item layui-show">
                        {if $id}
                        <input type="hidden" name="id" value="{$id}">
                        {/if}
                        <div class="layui-form-item">
                            <label for="goods_name" class="layui-form-label">商品名称</label>
                            <div class="layui-input-inline">
                                <input type="text" id="goods_name" name="goods_name" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.goods_name}">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-text">
                            <label for="goods_remark" class="layui-form-label">商品简介</label>
                            <div class="layui-input-inline">
                                <textarea placeholder="请输入内容" id="goods_remark" name="goods_remark" class="layui-textarea">{$result.goods_remark}</textarea>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="goods_sn" class="layui-form-label">商品货号</label>
                            <div class="layui-input-inline">
                                <input type="text" id="goods_sn" name="goods_sn" autocomplete="off" class="layui-input" value="{$result.goods_sn}">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                如果不填写，将会自动生成，请不要使用 "SD" 开头，因为 "SD" 是系统货号
                            </div>
                        </div>

                        <!-- 商品分类 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">商品分类</label>
                            <div class="layui-input-block" id="cate">

                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="shop_price" class="layui-form-label">商品售价</label>
                            <div class="layui-input-inline">
                                <input type="text" id="shop_price" name="shop_price" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.shop_price}" onfocus="isPrice(this)">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="market_price" class="layui-form-label">市场价</label>
                            <div class="layui-input-inline">
                                <input type="text" id="market_price" name="market_price" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.market_price}" onfocus="isPrice(this)">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="cost_price" class="layui-form-label">成本价</label>
                            <div class="layui-input-inline">
                                <input type="text" id="cost_price" name="cost_price" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.cost_price}" onfocus="isPrice(this)">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>
                            </div>
                        </div>

                        <div class="layui-upload layui-form-item">
                            <label class="layui-form-label">
                                <span class="x-red">*</span>商品主图
                            </label>
                            <button type="button" class="layui-btn layui-btn-normal" id="test8">选择文件</button>
                            <button type="button" class="layui-btn" id="test9">开始上传</button>
                            <input type="hidden" name="original_img" value="{$result.original_img}" id="ad_img">

                            <div class="layui-upload-list" style="display: {if !$result.original_img}none{/if};">
                                <label class="layui-form-label"></label>
                                <img class="layui-upload-img" id="demo1" src="{if $result}{:config('imgRoute')}{$result.original_img}{/if}">
                                <p id="demoText"></p>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="weight" class="layui-form-label">商品重量</label>
                            <div class="layui-input-inline">
                                <input type="text" id="weight" name="weight" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.weight}" onfocus="isNum(this)">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>设置商品重量, 用于计算物流费.以克为单位
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="volume" class="layui-form-label">商品体积</label>
                            <div class="layui-input-inline">
                                <input type="text" id="volume" name="volume" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.volume}" onfocus="isNum(this)">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>设置商品体积, 用于计算物流费.以立方米为单位
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">是否包邮</label>
                            <div class="layui-input-inline" id="is_free_shipping" lay-filter="is_free_shipping">
                                <input type="checkbox" name="is_free_shipping" {if isset($result.is_free_shipping)}{if $result.is_free_shipping == 1}checked=""{/if}{else /}checked=""{/if} value="{$result.is_free_shipping !== null ? $result.is_free_shipping : 1}" class="layui-input"
                                lay-skin="switch" lay-text="是|否">
                                <span style="margin-left: 8px;">运费模板</span>
                                <select name="template_id" id="template_id">
                                    <option value="">请选择运费模板</option>
                                    {volist name="template" id="v"}
                                        <option value="{$v.id}" {if $result.template_id == $v.id}selected{/if}>{$v.name}</option>
                                    {/volist}
                                </select>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="store_count" class="layui-form-label">总库存</label>
                            <div class="layui-input-inline">
                                <input type="text" id="store_count" name="store_count" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.store_count}" onfocus="isNum(this)">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="keywords" class="layui-form-label">关键词</label>
                            <div class="layui-input-inline" for="keywords">
                                <input type="text" id="keywords" name="keywords" autocomplete="off" class="layui-input" value="{$result.keywords}">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                多个关键词，用空格隔开
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-text">
                            <label for="goods_remark" class="layui-form-label">商品详情</label>
                            <div class="layui-input-block">
                                <textarea id="details" name="details" style="display: none;" lay-verify="content">{$result.details}</textarea>
                            </div>
                        </div>
                    </div>

                    <!-- 商品相册 -->
                    <div class="layui-tab-item">
                        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                            <legend>商品的详细组图</legend>
                        </fieldset>
                        <div class="layui-upload layui-form-item">
                            <button type="button" class="layui-btn layui-btn-normal" id="test11">选择文件</button>
                            <button type="button" class="layui-btn" id="test12">多图片上传</button>
                            <div id="hiddenImg">
                                {volist name="group_img" id="v"}
                                    <input type="hidden" name="group_img[]" value="{$v.img}" >
                                {/volist}
                            </div>
                            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;" id="uploadlist">
                                预览图：
                                <div class="layui-upload-list" id="demo2">
                                    {volist name="group_img" id="v"}
                                        <div class="show_img">
                                            <img src="{:config('imgRoute')}{$v.img}" alt="">
                                            <div class="is_del"><i class="layui-icon">&#xe640;</i></div>
                                            <span>上传成功</span>
                                        </div>
                                    {/volist}
                                </div>
                            </blockquote>
                        </div>
                    </div>

                    <!-- 商品模型 -->
                    <div class="layui-tab-item">
                        <div class="layui-form-item  layui-col-md8 layui-col-md-offset4">
                            <label class="layui-form-label">
                                <span class="x-red">*</span>商品模型
                            </label>
                            <div class="layui-input-inline">
                                <select name="model_id" lay-filter="model_id">
                                    <option value="">请选择商品模型</option>
                                    {volist name="goods_model" id="v"}
                                    <option value="{$v.id}" {if $result.model_id == $v.id}selected{/if}>{$v.model_name}</option>
                                    {/volist}
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div style="width: 65%; float: left;" id="spec_table">
                                <table class="layui-table lay-even"  style="margin-bottom: 0;">
                                    <colgroup>
                                        <col width="10%">
                                        <col width="90%">
                                    </colgroup>
                                    <thead>
                                        <tr>
                                            <th colspan="2">商品规格</th>
                                        </tr>
                                    </thead>
                                    <tbody id="spec">
                                        {volist name="result.spec" id="v"}
                                        <tr>
                                            <td>
                                                {$v.0.spec_name}
                                            </td>
                                            <td>
                                                {volist name="v" id="val"}
                                                <div>
                                                    <input type="checkbox" name="spec_item[{$val.spec_id}][item][{$val.id}]" data-name="{$val.spec_name}" data-id="{$val.spec_id}" {if isset($val.checked)}checked{/if} value="{$val.id}" title="{$val.item}" class="spec">
                                                    <div class="spec_img">
                                                        {if isset($val.img)}
                                                            {if $val.img}
                                                                <img src="{:config('imgRoute')}{$val.img}" alt="">
                                                            {else /}
                                                                <i class="layui-icon">&#xe681;</i>
                                                            {/if}
                                                        {else /}
                                                            <i class="layui-icon">&#xe681;</i>
                                                        {/if}
                                                        <input type="hidden" name="spec_item[{$val.spec_id}][img][{$val.id}]" value="{if isset($val.img)}{$val.img}{/if}">
                                                    </div>
                                                </div>
                                                {/volist}
                                            </td>
                                        </tr>
                                        {/volist}
                                    </tbody>
                                </table>

                                <table class="layui-table lay-even" style="margin-top: 0;" id="spec_item">
                                    <thead>
                                        <tr>
                                            <th class="var">内存</th>
                                            <th width="70">价格</th>
                                            <th width="70">库存</th>
                                            <th width="60">是否/有效</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td class="var_val"></td>
                                            <td><input type="text" name="price" autocomplete="off" class="layui-input" value="" onfocus="isPrice(this)"></td>
                                            <td><input type="text" name="stock" autocomplete="off" class="layui-input" value="" onfocus="isPrice(this)"></td>
                                            <td><input type="checkbox" name="switch" lay-text="是|否" checked lay-skin="switch"></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>

                            <table class="layui-table lay-even" style="width: 35%; float: left;">
                                <colgroup>
                                    <col width="30%">
                                    <col width="70%">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th colspan="2">商品属性</th>
                                    </tr>
                                </thead>
                                <tbody id="attr">
                                    {volist name="result.attr" id="v"}
                                    <tr>
                                        <td>
                                            <label>{$v.0.attr_name}</label>
                                        </td>
                                        <td>
                                            {if $v.0.input_mode == 1}
                                            <select name="attr_value[{$v.0.id}]">
                                                <option value="0">无</option>
                                                {volist name="v.attr_value" id="val"}
                                                <option value="{$val}" {if $val == $v.input_value}selected{/if}>{$val}</option>
                                                {/volist}
                                            </select>
                                            {else /}
                                            <input type="text" name="attr_value[{$v.0.id}]" autocomplete="off" class="layui-input" value="{$v.input_value}">
                                            {/if}
                                        </td>
                                    </tr>
                                    {/volist}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- 积分设置 -->
                    <div class="layui-tab-item">
                        <div class="layui-form-item">
                            <label for="give_integral" class="layui-form-label">赠送积分</label>
                            <div class="layui-input-inline">
                                <input type="text" id="give_integral" name="give_integral" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.give_integral ? $result.give_integral : 0}">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>购买商品可获得的积分
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label for="exchange_integral" class="layui-form-label">兑换积分</label>
                            <div class="layui-input-inline">
                                <input type="text" id="exchange_integral" name="exchange_integral" required="" lay-verify="required"
                                       autocomplete="off" class="layui-input" value="{$result.exchange_integral ? $result.exchange_integral : 0}">
                            </div>
                            <div class="layui-form-mid layui-word-aux">
                                <span class="x-red">*</span>兑换此商品所需要的积分，如果设置0， 此商品不支持积分兑换
                            </div>
                        </div>
                    </div>

                </div>
            </div>

          <div class="layui-form-item">
              <label for="L_repass" class="layui-form-label">
              </label>
              <button  class="layui-btn" lay-filter="edit" lay-submit="" id="L_repass">
                  {$result ? '修改' : '增加'}
              </button>
          </div>
      </form>
    </div>
    <script>
        formData('{:url("goods/goods_form")}', 'edit', function (){
            parent.location.reload();
            // 获得frame索引
            var index = parent.layer.getFrameIndex(window.name);
            //关闭当前frame
            parent.layer.close(index);
        }, false);

        $(function (){
            // 预加载商品分类
            var temp = '{$cate|raw}';
            temp = JSON.parse(temp);
            var num = 1;
            let str = '<option value="">请选择分类</option>';
            var len = Object.keys(temp).length;
            var width = parseInt(90/len) + '%';
            let appendLabel = '<select style="width: '+ width +'" name="cate" lay-filter="cate"></select>';
            for(var i = 0; i< len; i++){
                $("#cate").append(appendLabel);
            }
            let xing = '<div class="layui-form-mid layui-word-aux" style="flex-grow: 1;"><span class="x-red">*</span></div>';
            $("#cate").append(xing);

            for(var i in temp[num]){
                str += '<option value="' + temp[1][i]['id'] + '-'+ temp[1][i]['level'] +'">' + temp[1][i]['cate_name'] + '</option>';
            }
            $("select[name='cate']").eq(num - 1). html(str);

            // 预加载编辑器，表单
            layui.use(['form', 'layedit', 'upload'], function(){
                var form = layui.form;

                // 同步提交编辑器
                var layedit = layui.layedit;
                // 插入图片
                layedit.set({
                    uploadImage: {
                        url: '{:url("goods_upload")}'
                        ,type: 'post',
                    }
                });
                //建立编辑器
                var index = layedit.build('details');
                form.verify({
                    content: function(value) {
                        return layedit.sync(index);
                    }
                });

                var upload = layui.upload;
                // 上传图片
                uploadImg(upload, '{:url("goods_upload")}');

                var n_img = $(".show_img").length - 1 != -1 ? $(".show_img").length : 0;
                var files;
                //多图片上传
                upload.render({
                    elem: '#test11'
                    ,url: '{:url("goods_upload")}'
                    ,multiple: true
                    ,auto: false
                    ,accept: 'images'
                    ,field: 'img'
                    ,size: 2000
                    ,bindAction: '#test12'
                    ,choose: function (obj) {
                        files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列

                        //预读本地文件示例，不支持ie8
                        obj.preview(function (index, file, result) {
                            str = '<div class="show_img"><img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"><div class="is_del"><i class="layui-icon">&#xe640;</i></div></div>';
                            $('#demo2').append(str);
                            $('#uploadlist').css('display', 'block');
                            $("#test12").css('display', 'inline-block');
                        });
                    }
                    , before: function (obj) { //上传前回函数
                        layer.load(2); //上传loading
                    }
                    ,done: function(res){
                        layer.closeAll('loading');
                        //上传完毕
                        if(res.code == 1){
                            $("#test12").css('display', 'none');
                            $("#hiddenImg").append('<input type="hidden" name="group_img[]" value="'+ res.data.img +'" >');
                        }else{
                            $("#test12").html('重新上传');
                        }
                        $('#demo2 .show_img').eq(n_img).append('<span>'+ res.msg +'</span>');
                        n_img++;
                    }
                });

                // 显示图片删除按钮
                $("#demo2").on("mouseover mouseout", '.show_img', function(event){
                    if(event.type == "mouseover"){
                        $(this).children('.is_del').css('display', 'block');
                    }else if(event.type == "mouseout"){
                        $(this).children('.is_del').css('display', 'none');
                    }
                })

                // 图片删除
                $("#demo2").on('click', '.is_del', function (){
                    $(this).parent('.show_img').remove();
                    var filename = $(this).prev('img').attr('alt');
                    for(var i in files){
                        if(files[i].name == filename){
                            delete files[i];
                        }
                    }
                    n_img--;
                    $("#hiddenImg input").eq(n_img).remove();
                })

                // 选择运费模板
                $("#is_free_shipping").on('click', '.layui-form-switch', function (){
                    let status = $(this).prev().prop('checked');

                    if(status == false){
                        $("#template_id").next().css('display', 'inline-block');
                        $("#template_id").prev().css('display', 'inline-block');
                        $("#is_free_shipping .layui-form-switch").css('marginTop', '0');
                    }else{
                        $("#template_id").next().css('display', 'none');
                        $("#template_id").prev().css('display', 'none');
                        $("#is_free_shipping .layui-form-switch").css('marginTop', '8px');
                    }
                });

                // 修改表单执行操作
                var active_id = '{$result.cate_id !== false ? $result.cate_id : 0}';
                if(active_id != 0){
                    var currArr = pid(temp, active_id);

                    for(let n in temp){
                        var currStr = '<option value="">请选择分类</option>';

                        for(let j in temp[n]){
                            var currTemp = '';
                            for(let x in currArr){
                                if(currArr[x].id == temp[n][j].id){
                                    currTemp = 'selected';
                                }
                            }

                            currStr += '<option '+ currTemp +' value="' + temp[n][j]['id'] + '-'+ temp[n][j]['level'] +'">' + temp[n][j]['cate_name'] + '</option>';
                        }

                        $("select[name='cate']").eq(n - 1).html(currStr);
                    }
                    form.render('select');

                    for(let n in currArr){
                        $("select[name='cate']").eq(n).next().css('display', 'block');
                        if(currArr.length-1 == n){
                            $("select[name='cate']").eq(n).attr('name', 'cate_id');
                        }
                    }
                }

                // 商品分类信息处理
                form.on('select(cate)', function(data){
                    var value = data.value.split('-');
                    var id = value[0];
                    var num = parseInt(value[1]) + 1;

                    let arr = Infinite(temp, id, num);
                    $("select[name='cate_id']").attr('name', 'cate');
                    if(arr.length != 0){
                        let str = '<option value="">请选择分类</option>';
                        for(var i = 0; i < arr.length; i++){
                            str += '<option value="' + arr[i]['id'] + '-'+ arr[i]['level'] +'">' + arr[i]['cate_name'] + '</option>';
                        }

                        $("select[name='cate']").eq(num - 1). html('');
                        $("select[name='cate']").eq(num - 1). html(str);
                        form.render('select');

                        if(num > 2){
                            for(var i = 1; i < num; i++){
                                $("select[name='cate']").eq(i).next().css('display', 'block');
                            }
                        }else{
                            $("select[name='cate']").eq(num - 1).next().css('display', 'block');
                        }
                    }else{
                        $("select[name='cate']").eq(num - 2).attr('name', 'cate_id');

                        for(let i = 0; i < len; i++){
                            var val = $("select[name='cate']").eq(i).next().find('.layui-this').html();
                            if((typeof val) == 'undefined'){
                                if(i + 1 != len){
                                    $("select[name='cate']").eq(i + 1).next().css('display', 'none');
                                }
                            }
                        }
                    }
                });

                upload_item(upload);
                // 商品模型处理
                form.on('select(model_id)', function(data){
                    $("#spec_item tbody").html('');
                    let url = '{:url("goods/spec_attr")}';
                    let json = {'model_id': data.value};
                    $.post(url, json, function(res){
                        let attr = res.data.attr;
                        let spec = res.data.spec;

                        // 规格值
                        $("#spec").html('');
                        let html = '';
                        for(var i in spec){
                            html += '<tr>';
                            html += '<td>'+ spec[i][0].spec_name +'</td><td>';
                            for(var n in spec[i]){
                                html += '<div>';
                                html += '<input type="checkbox" data-id="'+spec[i][n].spec_id+'" data-name="'+ spec[i][n].spec_name +'" name="spec_item['+ spec[i][n].spec_id +'][item]['+ spec[i][n].id +']" value="'+ spec[i][n].id +'" title="'+ spec[i][n].item +'" class="spec">';
                                html += '<div class="spec_img"><i class="layui-icon">&#xe681;</i><input type="hidden" name="spec_item['+ spec[i][n].spec_id +'][img]['+ spec[i][n].id +']"></div>';
                                html += '</div>';
                            }
                            html += '</td></tr>';
                        }
                        $("#spec").html(html);
                        form.render('checkbox');

                        // 属性值
                        $("#attr").html('');
                        html = '';
                        for(var i in attr){
                            html += '<tr>';
                            html += '<td><label>'+ attr[i].attr_name +'</label></td>';
                            if(attr[i].input_mode == 1){
                                html += '<td><select name="attr_value['+ attr[i].id +']">';
                                html += '<option value="0">无</option>';
                                let arr = attr[i].attr_value.split('\n');
                                for(var n in arr){
                                    html += '<option value="'+ arr[n] +'">'+ arr[n] +'</option>';
                                }
                                html += '</select></td>';
                            }else{
                                html += '<td><input type="text" name="attr_value['+ attr[i].id +']" autocomplete="off" class="layui-input" value=""></td>';
                            }
                            html += '</tr>';
                        }
                        $("#attr").html(html);
                        form.render('select');

                        sepcPrice();
                        upload_item(upload);
                    }, 'json');
                });

                // 预加载商品规格
                sepcPrice();
                var isSepcPrice = '{$result.specPrice|raw}';
                if(isSepcPrice){
                    isSepcPrice = JSON.parse(isSepcPrice);
                    $("input[name$='[price]']").each(function (i, v){
                        var key = $(v).data('key');
                        var key_name = $(v).parent('td').next().children('input[name$="[key_name]"]');
                        var store = $(v).parent('td').next().children('input');
                        var status = $(v).parent('td').next().next().children('input');
                        for(var x in isSepcPrice){
                            if(isSepcPrice[x].key == key){
                                $(v).val(isSepcPrice[x].price);
                                store.val(isSepcPrice[x].store);
                                key_name.val(isSepcPrice[x].key_name);
                                var isCheck = isSepcPrice[x].status == 1 ? true : false;
                                status.prop('checked', isCheck);
                            }
                        }
                    });
                }
                form.render('checkbox');

                // 商品规格处理
                $("#spec").on('click', '.layui-form-checkbox', function (){
                    // 处理规格价格表
                    sepcPrice();
                    form.render('checkbox');
                })
            });

            $("#is_free_shipping").on('click', '.layui-form-switch', function (){
                var that = $(this).prev()
                var status = $(that).val() == 0 ? 1 : 0;
                $(that).val(status);
            });
        })

        // 商品的规格价格
        function sepcPrice(){
            var name = [];
            var prev_id = '', id = '', title = '';
            $("#spec").find('input').each(function(i, v){
                if($(v).prop('checked')){
                    prev_id = $(v).data('id');
                    id = $(v).val();
                    title = $(v).attr('title');

                    if(!name[prev_id]){
                        name[prev_id] = {};
                        name[prev_id].title = $(v).data('name');
                    }

                    var json = {};
                    json[id] = title;
                    if(!name[prev_id].value){
                        name[prev_id].value = [];
                    }

                    name[prev_id].value.push(json);
                }
            });
            // 过滤数组的空元素
            name = name.filter(d=>d);

            name = name.sort(compare('value'));

            var str = $("#spec_item thead .var").remove();

            var th,td,tr = '';
            var num = 1;
            for(var i in name){
                th += '<th class="var">'+ name[i].title +'</th>';

                num *= name[i].value.length;
            }
            $("#spec_item thead tr").prepend(th);

            var arr = [];
            for(var i in name){
                arr.push(name[i].value);
            }

            if(name.length != 0){
                arr2 = [];
                getArray(arr, 0, []);
                for(var i in arr2){
                    var key = '', key_name = '';
                    tr += '<tr>';
                    for(var n in arr2[i]){
                        var z = 1;
                        for(var x in arr2[i][n]){
                            // if(arr2[i-0+1] != null){
                            //     if(arr2[i-0+1][n] == arr2[i][n]){
                            //         z++;
                            //
                            //         tr += '<td class="var_val" rowspan="'+ z +'">'+ arr2[i][n][x] +'</td>';
                            //     }else{
                            //         if(arr2[i-1] != null){
                            //             if(arr2[i-1][n] != arr2[i][n]){
                            //                 tr += '<td class="var_val">'+ arr2[i][n][x] +'</td>';
                            //             }
                            //         }else{
                            //             tr += '<td class="var_val">'+ arr2[i][n][x] +'</td>';
                            //         }
                            //     }
                            // }else{
                            //     if(arr2[i-1] != null){
                            //         if(arr2[i-1][n] != arr2[i][n]){
                            //             tr += '<td class="var_val">'+ arr2[i][n][x] +'</td>';
                            //         }
                            //     }
                            // }

                            tr += '<td class="var_val">'+ arr2[i][n][x] +'</td>';

                            key += x + '_';
                            key_name += name[n].title + ':' + arr2[i][n][x] + ' ';
                        }
                    }

                    key = key.substr(0, key.length - 1);
                    key_name = key_name.substr(0, key_name.length - 1);
                    tr += '<td><input type="text" name="key['+ key +'][price]" data-key="'+ key +'" autocomplete="off" class="layui-input" value="0" onfocus="isPrice(this)"></td>';
                    tr += '<td><input type="text" name="key['+ key +'][store]" autocomplete="off" class="layui-input" value="0" onfocus="isPrice(this)">';
                    tr += '<input type="hidden" name="key['+ key +'][key_name]" autocomplete="off" class="layui-input" value="'+ key_name +'"></td>';
                    tr += '<td><input type="checkbox" name="key['+ key +'][status]" lay-text="是|否" checked lay-skin="switch"></td>';
                    tr += '</tr>';
                }
            }
            $("#spec_item tbody").html(tr);
        }

        function upload_item(upload, that){
            upload.render({
                elem: '.spec_img'
                ,url: '{:url("goods_upload")}'
                ,field: 'img'
                ,before: function(obj){
                    //预读本地文件示例，不支持ie8
                    var item = this.item;
                    item.children('input').val('');
                    var str = item.children('input').prop('outerHTML');

                    obj.preview(function(index, file, result){
                        str += '<img src="'+ result +'" alt="">';
                        item.html(str);
                    });
                }
                ,done: function(res){
                    var item = this.item;

                    if(res.code == 1){
                        item.children('input').val(res.data.img);
                    }else{
                        var str = item.children('input').prop('outerHTML');
                        str += '<i class="layui-icon">&#xe681;</i>';
                        item.html(str);
                    }
                }
                ,error: function(){
                    dialog('网络似乎开了一下小差……', false, 0);
                }
            });
        }

        // 数组归类
        var arr2 = [];
        function getArray(arr, i, newArr2) {
            for (let k = 0; k < arr[i].length; ++k) {
                newArr2.push(arr[i][k])
                var p = i + 1
                if (arr[p] != null) {
                    this.getArray(arr, p, newArr2)
                } else {
                    var a = []
                    Object.assign(a, newArr2)
                    arr2.push(a)
                }
                newArr2.pop();
            }
        }

        // 数组是否存在
        function IsInArray(arr,val){
            var testStr=','+arr.join(",")+",";

            return testStr.indexOf(","+val+",")!=-1;
        }

        // 当前分类处理
        var currCate = [];
        function pid(temp, active){
            var arr = [];
            for(var i in temp){
                var len = temp[i].length;
                for(var n = 0; n < len; n++){
                    if(temp[i][n].id == active){
                        currCate.push(temp[i][n]);
                        var active = temp[i][n].pid;
                        var test = pid(temp, active);
                        return currCate;
                    }
                }
            }

            return arr;
        }

        // 分类列表
        function Infinite(temp, id, num){
            var arr = [];
            if(temp[num]){
                for(var i in temp[num]){
                    if(temp[num][i]['pid'] == id){
                        arr.push(temp[num][i]);
                    }
                }
            }

            return arr;
        }

        // 数组排序
        function compare(property){
            return function(a,b){
                var value1 = a[property].length;
                var value2 = b[property].length;
                return value1 - value2;
            }
        }
    </script>
  {/block}